import Promise from 'promise';
import validator from 'validator';
import Git from 'nodegit';
import path from 'path';
import fs from 'fs';
import shell from 'shelljs';
import { RepoProxy } from '../proxy';

export {
  payload,
  fetch,
  list,
  add,
  del,
}

function clone(id, cloneUrl) {
  const repoDir = path.join(__dirname, 'public/repos', id.toString());
  shell.exec(`rm -rf ${repoDir}`);
  shell.exec(`mkdir ${repoDir}`);

  new Promise(function(resolve, reject) {
    Git.Clone(cloneUrl, repoDir).then(function() {
      shell.exec(`gitbook build ${repoDir}`);

      const configFile = path.join(repoDir, './config.json');
      const configContent = JSON.parse(fs.readFileSync(configFile));

      let data2 = {
        name: configContent.name,
        status: 1
      }

      RepoProxy.update(id, data2);
    });
  });
}

async function payload(req, res, next) {
  let payload = req.body.payload;
  payload = JSON.parse(payload);

  const { html_url, name } = payload.repository;
  const { login, avatar_url } = payload.repository.owner;

  try {
    const repo = await RepoProxy.findOne({cloneUrl: html_url});

    if (!repo) {
      throw new Error('Cannot found url');
    }

    let data = {
      gitLogin: login,
      gitName: name,
      gitAvatarUrl: avatar_url,
      status: 2
    };

    await RepoProxy.update(repo._id, data);
    clone(repo._id, repo.cloneUrl);
    res.json({msg: 'github webhook event deliver success'});
  } catch(err) {
    next(err);
  }
}

async function fetch(req, res, next) {
  const id = req.params.id;
  try {
    const repo = await RepoProxy.findOne({_id: id});
    if (!repo) {
      throw new Error('Cannot found url');
    }

    await RepoProxy.update(repo._id, {status: 2});
    clone(repo._id, repo.cloneUrl);
    res.json({msg: '正在拉取，1分钟后再刷新页面'});
  } catch(err) {
    next(err);
  }
}

async function list(req, res, next) {
  try {
    const docs = await RepoProxy.find({});
    res.json({msg: 'success', data: docs})
  } catch(err) {
    next(err);
  }
}

async function add(req, res, next) {
  const cloneUrl = req.body.cloneUrl;

  try {
    const docs = await RepoProxy.create(cloneUrl);
    res.json({msg: 'success'})
  } catch(err) {
    next(err);
  }
}

async function del(req, res, next) {
  const id = req.params.id;

  try {
    await RepoProxy.remove({_id: id});
    res.json({msg: 'success'})
  } catch(err) {
    next(err);
  }
}
